/**
  * Copyright (c) CSIRO Australia, 2009
  *
  * @author $Author: jia020 $
  * @version $Id: MessagesPanel.java 643 2009-05-20 00:20:55Z jia020 $
  */
package au.csiro.nt.pdsp.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.layout.FitLayout;
/**
 * MessagesPanel to manage the messages of user. 
 *
 */
public class MessagesPanel extends Panel {
	/**
	 * grid to show all the available messages. 
	 */
	private DynamicGrid grid = null;
	/**
	 * service point for rpc call. 
	 */	
	private final PDQueryServiceAsync service = GWT.create(PDQueryService.class);
	/**
	 * Constructor to create  MessagesPanel according to the xmlData. 
	 */	
	public MessagesPanel(String xmlData) {
		super();
		this.setBorder(false);
		this.setPaddings(5);
		this.setLayout(new FitLayout());

		grid = new DynamicGrid(xmlData);
		Toolbar toolbar = new Toolbar();

		ToolbarButton buttonAccept = new ToolbarButton("Authorize",
				new ButtonListenerAdapter() {
					public void onClick(Button button, EventObject e) {
						sendMessage(PdspConst.IMS_MESSAGE_AUTHORIZED);
					}
				});
		ToolbarButton buttonReject = new ToolbarButton("Reject",
				new ButtonListenerAdapter() {
					public void onClick(Button button, EventObject e) {
						sendMessage(PdspConst.IMS_MESSAGE_REJECTED);
					}
				});
		toolbar.addButton(buttonAccept);
		toolbar.addButton(buttonReject);
		this.add(grid);
		this.add(toolbar);

	}
	/**
	 * send Message to server by rpc call.
	 *  @param message
	 */	
	private void sendMessage(String message) {
		final Record selectedRecord = grid.getSelectionModel().getSelected();
		if (selectedRecord == null)
			return;
		int imsID = selectedRecord.getAsInteger("imsid");
		service.sendMessage(imsID, message, new AsyncCallback<Boolean>() {
			public void onFailure(Throwable caught) {
				MessageBox.alert("failed:sendMessage!");
			}

			@Override
			public void onSuccess(Boolean result) {
				grid.store.remove(selectedRecord);
				MessageBox.alert("Success:sendMessage!");
			}
		});
	}
}
